package com.neusoft.nepg.gridders.controller;

import com.neusoft.nepg.gridders.entity.User;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;

import static com.neusoft.nepg.gridders.utils.AlertUtils.showDialog;
import static com.neusoft.nepg.gridders.utils.FileUtils.mapReader;
import static com.neusoft.nepg.gridders.utils.FileUtils.mapWriter;

public class LoginController implements Initializable {
    @FXML
    private TextField username;
    @FXML
    private PasswordField password;
    @FXML
    private Button login;

    @FXML
    public void login() throws IOException {
        //get username and password
        String name = username.getText();
        String pass = password.getText();
        //check username and password
        Map<String, User> userMap = mapReader("/resource/user.txt");
        if (!userMap.containsKey(name)) showDialog("user not exist!");
        else if (!userMap.get(name).getPass().equals(pass)) showDialog("wrong password!");
        else {
            //get current stage
            Stage stage = (Stage) login.getScene().getWindow();
            //get next page
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/FeedbackListView.fxml"));
            //reform format
            Parent root = fxmlLoader.load();
            Scene scene = new Scene(root);
            //set scene
            stage.setScene(scene);
        }
    }

    public void initialize(URL location, ResourceBundle resources) {
        //set default username and password
        User user = new User("admin", "admin", "12345678901", "admin@123.com");
        Map<String, User> userMap = mapReader("user.txt");
        userMap.put(user.getName(), user);
        mapWriter("user.txt", userMap);
    }
}
